package com.speedchina.common.message.wechat.util;
import com.speedchina.common.message.util.SendResult;
import com.speedchina.common.message.wechat.message.Message;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.util.EntityUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

/**
 * 发送消息工具类
 * @author zyw
 */
public class WxChatbotClient {

    static HttpClient httpclient = HttpClients.createDefault();

    /**
     * 统一进行send发送
     * @param webhook webhook地址
     * @param message 终究是个json
     * @return
     * @throws IOException
     */
    public static SendResult send(String webhook, Message message) throws IOException{
    	if(StringUtils.isBlank(webhook)){
    		return new SendResult();
    	}
        HttpPost httppost = new HttpPost(webhook);
        httppost.addHeader("Content-Type", "application/json; charset=utf-8");
        StringEntity se = new StringEntity(message.toJsonString(), "utf-8");
        httppost.setEntity(se);
        SendResult sendResult = new SendResult();
        org.apache.http.HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity());
            JSONObject obj = JSONObject.parseObject(result);
            Integer errcode = obj.getInteger("errcode");
            sendResult.setErrorCode(errcode);
            sendResult.setErrorMsg(obj.getString("errmsg"));
            sendResult.setSuccess(errcode.equals(0));
            sendResult.setSuccessMsg("企业微信机器人报警成功");
        }
        return sendResult;
    }

//    @SneakyThrows
//    public String getFilemedia_id(MultipartFile file, String filename){
//        InputStreamResource isr = null;
//        isr=new InputStreamResource(file.getInputStream(), file.getOriginalFilename());
//        HttpUtil.post
//    }
}


